console.log('hi');
const path = require('path');

/**
 * 这段代码可以发出stageXxx.json和其中的stageId不一致的警告
 * 同时生成BlockIdFromStage.ts文件，该文件可以对优化游戏启动速度提供指导
 * 使用方式：在当前文件目录下，运行 node genBlockIdFromStage.js
 */

// 获取当前文件的目录
const directoryPath = __dirname;
console.log("Directory Path:", directoryPath);

const jsonDir = path.join(directoryPath, '../Game110Client/assets/ab_lobby/Json');
const scriptsDir = path.join(directoryPath, '../Game110Client/assets/ab_lobby/scripts');

console.log("jsonDir", jsonDir);

// 读取目录中的.json文件
const fs = require('fs');
const files = fs.readdirSync(jsonDir);
const jsonFiles = files.filter(file => path.extname(file) === '.json');

// 解析每个.json文件并分析其中"id"字段的值

let blockIdFromStage = {};
for (let i = 1; i <= 31; i++) {
    blockIdFromStage[i] = 999999;
}

let hardStageRecord = {};

for (const file of jsonFiles) {
    const regex = /stage(\d+)\.json/;
    const match = file.match(regex);
    if (match) {
        const stageNum = match[1];

        const filePath = path.join(jsonDir, file);
        const jsonData = fs.readFileSync(filePath);
        const data = JSON.parse(jsonData);

        let stageId = data.stageId;

        if (stageNum != stageId) {
            console.warn(`Please check: stageNum:${stageNum}, stageId:${stageId}`);
            stageId = stageNum;
        }

        let blockIds = Array.from(new Set(data.blocks.map(block => block.blockId)));

        // console.log(`stageId:${stageId}, blockIds:${blockIds}`);

        for (let i = 0; i < blockIds.length; i++) {
            let blockId = blockIds[i];
            if (stageId < blockIdFromStage[blockId]) {
                blockIdFromStage[blockId] = stageId;
            }
        }

        if (data.hard == 1) {
            hardStageRecord[data.stageId] = 1;
        }
    } else {
        console.warn(`Can not find stageNum in fileName:${file}`);
    }


}

console.log('blockIdFromStage', blockIdFromStage);
console.log('hardStageRecord', hardStageRecord);

// 把blockIdFromStage写入文件

let codeText = `export const BlockIdFromStage = ${JSON.stringify(blockIdFromStage, null, 4)};`;
fs.writeFileSync(path.join(scriptsDir, 'BlockIdFromStage.ts'), codeText);

let codeText_hard = `export const HardStageRecord = ${JSON.stringify(hardStageRecord, null, 4)};`;
fs.writeFileSync(path.join(scriptsDir, 'HardStageRecord.ts'), codeText_hard);